# 二叉树
class BTree:

    class Node:
        def __init__(self, data):
            self.data = data
            self.count = 1
            self.left = None
            self.right = None
            self.i = 0
            self.data_arr = []

        def add_child(self, node):
            if node.data >= self.data:
                if self.right:
                    self.right.add_child(node)
                else:
                    self.right = node
            else:
                if self.left:
                    self.left.add_child(node)
                else:
                    self.left = node
            self.count += 1

        # 中序遍历
        def to_array(self, arr):
            if self.left:
                self.left.to_array(arr)
            arr.append(self.data)
            if self.right:
                self.right.to_array(arr)

        def __next__(self):
            # __next__实现迭代部分，迭代结束raise StopIteration()
            if self.data_arr is None or len(self.data_arr) == 0:
                self.to_array(self.data_arr)
            if self.i < self.count:
                tmp = self.data_arr[self.i]
                self.i += 1
                return tmp
            self.i = 0
            self.data_arr = []
            raise StopIteration()

    def __init__(self, data):
        self.root = self.Node(data)
        self.count = 1

    def add(self, data):
        node = self.Node(data)
        self.root.add_child(node)
        self.count += 1

    def to_array(self):
        obj_arr = []
        self.root.to_array(obj_arr)
        return obj_arr

    def __iter__(self):
        # __iter__要求返回一个实现了__next__的对象，自身实现了则直接返回self
        return self.root


if __name__ == '__main__':
    btree = BTree('E')
    btree.add('C')
    btree.add('A')
    btree.add('D')
    btree.add('B')
    btree.add('F')
    print(btree.count)
    # for x in btree.to_array():
    #     print(x)
    for x in btree:
        print(x)
